package com.cnyz.intercept;

import cn.hutool.core.map.MapUtil;
import com.cnyz.constant.Constants;
import com.cnyz.constant.SecurityConstant;
import com.cnyz.exception.BaseException;
import com.cnyz.properties.JwtTokenManagerProperties;
import com.cnyz.utils.JwtUtil;
import com.cnyz.utils.ObjectUtil;
import com.cnyz.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private JwtTokenManagerProperties jwtTokenManagerProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //不映射到方法放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        String token = request.getHeader(SecurityConstant.USER_TOKEN);

        if(ObjectUtil.isEmpty(token)){
            throw new BaseException("用户登录","401",null,"没有权限请登录");
        }

        Map<String,Object> claims= JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),token);

        //token失效
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException("用户登录","401",null,"token失效");
        }

        Long userId= MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        if(ObjectUtil.isEmpty(userId)){
            throw new BaseException("用户登录","401",null,"token失效");
        }

        UserThreadLocal.set(userId);
        return true;

    }

    //竞争后移除用户线程
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
